<template>
  <!-- <van-nav-bar title="猫眼电影" left-arrow :fixed="true" @click-left="onClickLeft">
  </van-nav-bar> -->

  <NavBarCmp :leftArrow="true" />

  <van-search class="search-input" v-model="value" show-action :formatter="formatter" format-trigger="onChange"
    clear-trigger="always" placeholder="搜电影、搜影院" @cancel="onCancel" @update:model-value="onUpdate" @clear="onClear"
    @focus="onFocus" />

  <!-- 最近搜索关键词 -->
  <van-list v-show="toggleKeywords" class="keywords-list">
    <van-cell v-for="(searchKeyword, index) in searchHistory" :key="index" :title="searchKeyword" icon="clock-o"
      @click="onClick(searchKeyword)">
      <template #right-icon>
        <van-icon name="clear" @click.stop="deleteHistory(searchKeyword)" size="18" />
      </template>
    </van-cell>
  </van-list>
  <!-- 搜索结果  电影/电视剧/综艺-->
  <div class="search-result">
    <p class="result-title" v-if="movieTotal > 0">电影/电视剧/综艺</p>
    <ul>
      <li class="search-result-item" v-for="movie in movieList" :key="movie.id">
        <img :src="movie.img" :alt="movie.nm" />
        <div class="movie-info">
          <div class="title line-ellipsis">{{ movie.nm }} <span class="version"
              :class="movieVersion(movie.version)"></span>
          </div>

          <div class="english-title line-ellipsis">{{ movie.enm }}</div>
          <div class="type line-ellipsis">{{ movie.cat }}</div>
          <div class="showInfo line-ellipsis">{{ movie.pubDesc }}</div>
        </div>
        <div class="score-buy">
          <span class="score">{{ movie.sc }}<span>分</span></span>
          <van-button class="buy" round size="small" v-if="movie.showStateButton"
            :color="movie.showStateButton.color">{{
              movie.showStateButton.content
            }}</van-button>
        </div>
      </li>
    </ul>

    <van-button plain hairline block square size="normal" class="more-btn" v-show="movieTotal > 0"
      @click="onClickMore('movies')">查看全部{{ movieTotal
      }}部影视剧</van-button>

    <p class="result-title" v-if="cinemaTotal > 0">影院</p>


    <ul>
      <li v-for="cinema in cinemaList" :key="cinema.id" class="cinema-item">
        <van-row class="title">
          <van-col class="line-width line-ellipsis">{{ cinema.nm }}</van-col>
          <van-col class="price">{{ cinema.sellPrice }} <span>元起</span></van-col>
        </van-row>
        <van-row class="location">
          <van-col class="line-ellipsis line-width">{{ cinema.addr }}</van-col>
        </van-row>
        <van-row class="services" v-show="cinema.hallType">
          <van-col v-for="(item, index) in cinema.hallType" :key="index"><van-tag plain type="primary">{{ item
              }}</van-tag></van-col>
        </van-row>
      </li>
    </ul>
    <van-button plain hairline block square size="normal" class="more-btn" v-show="cinemaTotal > 0"
      @click="onClickMore('cinemas')">查看全部{{ cinemaTotal
      }}家影院</van-button>

    <!-- 404-->
    <div class="nothing" v-if="nothing">
      <van-image :src="nothingImg" width="100" :block="true" />
      <p>没有找到相关的内容</p>
    </div>

    <!-- loading-->
    <van-loading type="spinner" color="#f03d37" class="loading" v-show="loading" />

  </div>
</template>
<script setup>


import { useHead } from '@unhead/vue'

useHead({
  title: '搜索-猫眼电影'
})


import nothingImg from "@/assets/nothing.png";
import { fetchSearchSuggestions } from "@/api/index.js";
import { useRouter } from 'vue-router';
const router = useRouter();
import { useStore } from "@/stores/index.js"
const store = useStore();
import { ref, onMounted, computed, watch } from 'vue';

const value = ref('');

const keyword = ref('') //搜索关键词

const movieList = ref([]); //搜索结果列表
const cinemaList = ref([]); //影院列表
const movieTotal = ref(0); //查询结果数量
const cinemaTotal = ref(0); //查询结果数量

// const searchHistory = ref([]);
const toggleKeywords = ref(false) //是否显示最近搜索关键词

const searchHistory = computed(() => {  //最近3个搜索关键词
  return store.searchHistory
})

const nothing = ref(false) //是否显示404页面
const loading = ref(false) //是否显示loading


//电影版本
const movieVersion = (version) => {
  if (version === 'v2d') {

    return 'v2d'
  } else if (version === 'v2d imax') {

    return 'v2dimax'
  } else if (version == 'v3d') {
    return 'v3d'
  }
  else if (version == 'v3d imax') {
    return 'v3dimax'
  }
  else {
    return ''
  }

}



onMounted(() => {
  toggleKeywords.value = true
})

// 点击选择某个最近搜索关键词
const onClick = async (searchKeyword) => {
  console.log("最近搜索关键词：", searchKeyword);

  keyword.value = searchKeyword

  console.log("keyword.value", keyword.value);


  const response = await fetchSearchSuggestions(searchKeyword, store.currentCity.id)
  if (response.success) {
    // console.log("response", response);
    if (response.movies && response.movies.list.length > 0) {

      movieList.value = response.movies.list
      movieTotal.value = response.movies.total
      nothing.value = false
    }

    if (response.cinemas && response.cinemas.list.length > 0) {
      cinemaList.value = response.cinemas.list
      cinemaTotal.value = response.cinemas.total
      nothing.value = false
    }

    if (!response.movies && !response.cinemas) {
      nothing.value = true
    }
    //保存最近3个搜索关键词
    // searchHistory.value.unshift(keyword)
    store.setSearchHistory(keyword)
  }
  toggleKeywords.value = false

}

const onClickLeft = () => {
  router.go(-1)
};
const formatter = (input) => {
  return input.replace(/\s+/g, '')
}
const onUpdate = async (value) => {
  console.log("搜索关键词：", value);
  //注意过滤清除的空值,只有值非空的时候才传入API查询
  if (value != '') {
    keyword.value = formatter(value)
    loading.value = true;
    //发往API进行搜索查询
    const response = await fetchSearchSuggestions(value, store.currentCity.id)
    if (response.success) {
      // console.log("response", response);
      if (response.movies && response.movies.list.length > 0) {

        movieList.value = response.movies.list
        movieTotal.value = response.movies.total
        nothing.value = false
      }

      if (response.cinemas && response.cinemas.list.length > 0) {
        cinemaList.value = response.cinemas.list
        cinemaTotal.value = response.cinemas.total
        nothing.value = false
      }

      // 显示404
      if (!response.movies && !response.cinemas) {
        nothing.value = true
      }
      //保存最近3个搜索关键词
      // searchHistory.value.unshift(value)
      store.setSearchHistory(value)
      loading.value = false;
    }
  } else {
    //清空
    movieList.value = []
    movieTotal.value = 0
    cinemaList.value = []
    cinemaTotal.value = 0
    nothing.value = false
  }
};

const onFocus = () => {
  toggleKeywords.value = false
}


const deleteHistory = (keyword) => {
  // console.log("deleteHistory 点击X");
  //删除指定的搜索关键词
  store.deleteSearchHistory(keyword)

  // 检查 searchHistory 是否为空 确保不显示404
  if (store.searchHistory.length === 0) {
    nothing.value = false
  }

}

const onClear = () => {
  //清空内容
  value.value = ''
  movieList.value = []
  movieTotal.value = 0

  cinemaList.value = []
  cinemaTotal.value = 0

  // 检查 searchHistory 是否为空 确保不显示404
  if (store.searchHistory.length === 0) {
    nothing.value = false;
  }
}

// 取消搜索，返回首页
const onCancel = () => {
  router.push({ path: '/' })
};



const onClickMore = (searchType) => {

  router.push({ name: 'searchList', params: { searchType: searchType }, query: { keyword: keyword.value } })
};



</script>
<style scoped>
.line-ellipsis {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  width: 100%;
}

.search-input {
  margin-top: 50.5px;
  /* padding-bottom: 0px !important; */
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

:deep(.van-search__action) {
  color: #f03d37;
}

.keywords-list {
  z-index: 100
}


.search-result {

  position: relative;
  height: auto;
}

.search-result .result-title {
  color: #999;
  font-size: 15px;
  border-bottom: 1px solid #eee;
  margin: 0;
  padding: 10px;

}

ul {
  padding: 0 10px;
}


.search-result-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  padding: 10px;
  justify-content: flex-start;
  border-bottom: 1px solid #eee;
}

.search-result-item .movie-info {
  width: calc(100% - 124px);
}


.search-result-item .movie-info .title {
  color: #222;
  font-size: 17px;
  font-weight: 700;
  margin-bottom: 5px;
  height: 30px;
  line-height: 30px;

}


.search-result-item .movie-info .english-title,
.search-result-item .movie-info .type,
.search-result-item .movie-info .showInfo {
  color: #666;
  font-size: 13px;
  margin-bottom: 5px;
}



.search-result-item img {
  width: 64px;
  height: 90px;
  margin-right: 10px;
}


.search-result-item .score-buy {
  width: 60px;
  color: #fa0;
  font-size: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;

}


.search-result-item .score-buy .score {
  color: #fa0;
  font-size: 16px;
  margin-bottom: 10px;
}

.search-result-item .score-buy span {
  font-size: 10px;
}



.buy {
  color: #fff;
  font-size: 13px;
  width: 60px;
  height: 32px;
  line-height: 32px;
}

.more-btn {
  color: #ef4238;
  font-size: 15px;
  margin-bottom: 10px;
}


.version {
  background-size: contain;
  background-repeat: no-repeat;
  width: 50px;
  height: 14px;
  line-height: normal;
  display: inline-block;
}


.version.v2d {
  background-image: url("@/assets/version/v2d.png");
}

.version.v2dimax {
  background-image: url("@/assets/version/v2dimax.png");
}

.version.v3d {

  background-image: url("@/assets/version/v3d.png");
}


.version.v3dimax {
  background-image: url("@/assets/version/v3dimax.png");
}



.cinema-item {
  border-bottom: 1px solid #eee;
  padding: 10px 0;
}

.cinema-item:last-child {
  border: 0;
}

.cinema-item .services .van-tag {
  font-size: 10px;
  margin-right: 5px;
}

.cinema-item .title {
  color: #000;
  font-size: 16px;
  flex-wrap: nowrap;
  margin-bottom: 10px;
  justify-content: space-between;
  align-items: center;
}

.cinema-item .title .val-col {
  width: 200px;
}

.cinema-item .title .price {
  color: #f03d37;
}

.cinema-item .title .price span {
  font-size: 11px;
}

.cinema-item .location {
  color: #666;
  font-size: 13px;
  white-space: nowrap;
  text-overflow: ellipsis;
  width: 100%;
  overflow: hidden;
  flex-wrap: nowrap;
  margin-bottom: 10px;
}

.cinema-item .location .val-col {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  width: 100%;
}


.nothing {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: calc(100vh - 50.5px - 55px);
  /* 根据需要调整高度 */
  text-align: center;
}

.nothing p {
  font-size: 16px;
  color: #999;
}

.loading {

  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: calc(100vh - 50.5px - 55px);
  /* 根据需要调整高度 */
  text-align: center;
  z-index: 5;
}

.van-cell {
  cursor: pointer;
}
</style>
